package com.skillworld.webapp.web.pages.rest.school;

import java.util.Locale;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.course.Course;
import com.skillworld.webapp.model.courseservice.CourseService;
import com.skillworld.webapp.model.util.PermissionDeniedException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class CreateCourse 
{
	
	@SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @SuppressWarnings("unused")
    @Property
    private Course course;
    
    @Inject
    private CourseService courseService;
    
    @SessionState(create=false)
    private UserSession userSession;
   
    private boolean userSessionExists;
    
    @Inject
    private Request request;
	
    
    void onPassivate()
    {
        return;
    }
    
    void onActivate()
    {        
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String deptParam = request.getParameter("dept");
        String name = request.getParameter("name");
        String description = request.getParameter("desc");
        String langParam = request.getParameter("lang");
        String maxstudentsParam = request.getParameter("max-students");
        
        if (deptParam ==null || name== null || description == null 
                || langParam == null || maxstudentsParam == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
        
        try
        { 
        	long departmentId = Long.parseLong(deptParam);
        	Locale locale = new Locale(langParam);
        	int maxStudents = Integer.parseInt(maxstudentsParam);
            course = courseService.createCourse(name, description, 
                                                locale, maxStudents, 
                                                userSession.getUserId(), 
                                                departmentId);
        }
        catch (NumberFormatException e) 
        { errorMessage = ErrorMessages.PERMISSION_DENIED; }
        catch (PermissionDeniedException e) 
        { errorMessage = ErrorMessages.PERMISSION_DENIED; } 
        catch (InstanceNotFoundException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
    }
}
    

